<template>
  <div class="negotiation-detail-container">
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <el-button icon="ArrowLeft" type="text" @click="goBack">返回</el-button>
          <span class="header-title">协商详情</span>
          <div class="header-actions">
            <el-button 
              v-if="negotiation && negotiation.status === 0"
              type="primary" 
              size="small" 
              @click="goToChat"
            >
              继续聊天
            </el-button>
          </div>
        </div>
      </template>

      <el-skeleton :loading="loading" animated>
        <template #template>
          <div style="padding: 20px">
            <el-skeleton-item variant="text" style="width: 30%; margin-bottom: 15px" />
            <el-skeleton-item variant="text" style="width: 50%; margin-bottom: 15px" />
            <el-skeleton-item variant="text" style="width: 40%; margin-bottom: 15px" />
            <el-skeleton-item variant="text" style="width: 60%; margin-bottom: 15px" />
            <el-skeleton-item variant="text" style="width: 35%; margin-bottom: 15px" />
          </div>
        </template>

        <template #default>
          <div v-if="negotiation" class="negotiation-info">
            <div class="info-section">
              <div class="section-title">基本信息</div>
              <div class="info-row">
                <span class="info-label">协商状态：</span>
                <el-tag :type="getStatusType(negotiation.status)">
                  {{ getStatusText(negotiation.status) }}
                </el-tag>
              </div>
              <div class="info-row">
                <span class="info-label">创建时间：</span>
                <span>{{ formatDateTime(negotiation.createdTime) }}</span>
              </div>
              <div class="info-row" v-if="negotiation.updatedTime">
                <span class="info-label">更新时间：</span>
                <span>{{ formatDateTime(negotiation.updatedTime) }}</span>
              </div>
            </div>

            <div class="info-section">
              <div class="section-title">参与方信息</div>
              <div class="info-row">
                <span class="info-label">广告主：</span>
                <span>{{ negotiation.advertiserName }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">设备主：</span>
                <span>{{ negotiation.deviceOwnerName }}</span>
              </div>
            </div>

            <div class="info-section">
              <div class="section-title">广告信息</div>
              <div class="info-row">
                <span class="info-label">广告ID：</span>
                <span>{{ negotiation.adId }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">广告名称：</span>
                <span>{{ negotiation.advertisementName }}</span>
              </div>
            </div>

            <div class="info-section">
              <div class="section-title">协商详情</div>
              <div class="negotiate-price">
                <span class="info-label">协商价格：</span>
                <span class="price-value">¥{{ negotiation.price }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">播放时段：</span>
                <div class="time-slots">
                  <el-tag
                    v-for="(slot, index) in negotiation.timeSlots"
                    :key="index"
                    type="success"
                    effect="plain"
                    class="time-slot-tag"
                  >
                    {{ slot.startTime }} - {{ slot.endTime }}
                  </el-tag>
                </div>
              </div>
              <div class="info-row">
                <span class="info-label">协商内容：</span>
                <div class="negotiation-content">
                  {{ negotiation.content }}
                </div>
              </div>
            </div>

            <div class="action-buttons" v-if="negotiation.status === 0">
              <el-button 
                type="success" 
                @click="completeNegotiation"
                :loading="actionLoading"
              >
                完成协商
              </el-button>
              <el-button 
                type="danger" 
                @click="cancelNegotiation"
                :loading="actionLoading"
              >
                取消协商
              </el-button>
            </div>
          </div>
          <el-empty v-else description="未找到协商信息"></el-empty>
        </template>
      </el-skeleton>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';
import { getNegotiationDetail, completeNegotiation as completeNegotiationapi, cancelNegotiation as cancelNegotiationapi  } from '@/api/negotiation';

const route = useRoute();
const router = useRouter();
const negotiationId = ref(route.params.id);
const negotiation = ref(null);
const loading = ref(true);
const actionLoading = ref(false);

// 获取协商详情
const fetchNegotiationDetail = async () => {
  try {
    loading.value = true;
    const res = await getNegotiationDetail(negotiationId.value);
    console.log('协商详情', res);
    if (res.data.code === 200) {
      negotiation.value = res.data.data;
    } else {
      ElMessage.error(res.message || '获取协商详情失败');
    }
  } catch (error) {
    console.error('获取协商详情失败', error);
    ElMessage.error('获取协商详情失败');
  } finally {
    loading.value = false;
  }
};

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'warning',  // 进行中
    1: 'success',  // 已完成
    2: 'info'      // 已取消
  };
  return statusMap[status] || 'info';
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '进行中',
    1: '已完成',
    2: '已取消'
  };
  return statusMap[status] || '未知';
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 前往聊天页面
const goToChat = () => {
  router.push({
    path: `/advertiser/chat/${negotiationId.value}`
  });
};

// 完成协商
const completeNegotiation = async () => {
  try {
    await ElMessageBox.confirm('确定要完成此协商吗？完成后将进入合约生成阶段。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    actionLoading.value = true;
    const res = await completeNegotiationapi(negotiationId.value);
    if (res.code === 200) {
      ElMessage.success('协商已完成');
      // 刷新数据
      fetchNegotiationDetail();
    } else {
      ElMessage.error(res.message || '操作失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成协商失败', error);
      ElMessage.error('操作失败');
    }
  } finally {
    actionLoading.value = false;
  }
};

// 取消协商
const cancelNegotiation = async () => {
  try {
    await ElMessageBox.confirm('确定要取消此协商吗？取消后将不可恢复。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    actionLoading.value = true;
    const res = await cancelNegotiationapi(negotiationId.value);
    if (res.code === 200) {
      ElMessage.success('协商已取消');
      // 刷新数据
      fetchNegotiationDetail();
    } else {
      ElMessage.error(res.message || '操作失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消协商失败', error);
      ElMessage.error('操作失败');
    }
  } finally {
    actionLoading.value = false;
  }
};

onMounted(() => {
  fetchNegotiationDetail();
});
</script>

<style scoped>
.negotiation-detail-container {
  padding: 20px;
}

.detail-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.negotiation-info {
  padding: 10px 0;
}

.info-section {
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.info-section:last-child {
  border-bottom: none;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
}

.info-row {
  display: flex;
  margin-bottom: 10px;
  align-items: flex-start;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  width: 120px;
  color: #606266;
  flex-shrink: 0;
}

.negotiate-price {
  display: flex;
  margin-bottom: 15px;
  align-items: center;
}

.price-value {
  font-size: 20px;
  font-weight: bold;
  color: #F56C6C;
}

.time-slots {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.time-slot-tag {
  margin-right: 0;
}

.negotiation-content {
  background-color: #f8f8f8;
  padding: 15px;
  border-radius: 4px;
  color: #303133;
  white-space: pre-line;
  flex: 1;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}
</style> 